package com.software.myopiaparents.fragment;


import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.provider.CallLog;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.software.myopiaparents.R;
import com.software.myopiaparents.base.BaseFragment;
import com.software.myopiaparents.bean.AlertListInfo;
import com.software.myopiaparents.content.Constant;
import com.software.myopiaparents.http.HostType;
import com.software.myopiaparents.http.HttpApi2;
import com.software.myopiaparents.utils.ToastUtil;
import com.software.myopiaparents.utils.eb.EB;
import com.software.myopiaparents.utils.eb.EbData;
import com.software.myopiaparents.utils.perm.NetworkUtils;
import com.software.myopiaparents.utils.sp.SP;

import org.greenrobot.eventbus.Subscribe;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @author penglei
 * @date 2020/05/19
 * 警报类型
 */
public class AlarmFragment extends BaseFragment {
    private static final String TAG = "AlarmFragment";

    @BindView(R.id.tv_empty_hint)
    TextView mTvEmptyHint;
    @BindView(R.id.iv_empty_image)
    ImageView mIvEmptyImage;
    @BindView(R.id.rl_empty_layout)
    RelativeLayout mRlEmptyLayout;
    @BindView(R.id.rv_list)
    RecyclerView mRvList;
    @BindView(R.id.lay_refresh)
    SmartRefreshLayout mLayRefresh;

    private boolean refreshType;
    private int page = 1; // 页数
    private final int items = 10; // 每页条数
    private int total_page; // 总页数

    private int type = 1; // 警报类型

    private List<AlertListInfo.DataBean.ListBean> mData = new ArrayList<>();
    private BaseQuickAdapter<AlertListInfo.DataBean.ListBean, BaseViewHolder> mAdapter;

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_alarm;
    }

    @Override
    public void initView() {
        EB.register(this);
        // RecyclerView
        mRvList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRvList.setNestedScrollingEnabled(false);
        mRvList.setHasFixedSize(true);
        mRvList.setFocusable(false);

        // 开启自动加载功能（非必须）
        mLayRefresh.setEnableAutoLoadMore(false);
        mLayRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                page = 1;
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshType = true;
                        getAlarmList(page, type);
                        refreshLayout.finishRefresh();
                        refreshLayout.resetNoMoreData();//setNoMoreData(false);
                    }
                }, 2000);
            }
        });
        mLayRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                page++;
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshType = false;
                        if (page > total_page) {
                            ToastUtil.showShort(getResources().getString(R.string.toast_no_more_data));
                            // 将不会再次触发加载更多事件
                            refreshLayout.finishLoadMoreWithNoMoreData();
                            return;
                        }
                        getAlarmList(page, type);
                        refreshLayout.setEnableLoadMore(true);
                        refreshLayout.finishLoadMore();
                    }
                }, 2000);
            }
        });
        //触发自动刷新
//        mLayRefresh.autoRefresh();
    }

    @Override
    public void initData() {
        type = getArguments().getInt("type");
        getAlarmList(page, type);
    }


    @Override
    public void onDestroy() {
        EB.unregister(this);
        super.onDestroy();
    }


    @Subscribe
    public void onEvent(EbData data) {
        if (data.getType() == 1001 && type == 1) {
            refreshType = true;
            getAlarmList(1, 1);
        } else if (data.getType() == 1002 && type == 2) {
            refreshType = true;
            getAlarmList(1, 2);
        }
    }

    /**
     * 警报提示列表
     */
    private void getAlarmList(int page, int type) {
        String jwt_token = new SP().load(Constant.USER_JWT_TOKEN, "");
        if (NetworkUtils.isConnected(getActivity())) {
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", jwt_token);

            Map<String, String> params = new HashMap<>();
            params.put("pageIndex", page + "");
            params.put("pageSize", 10 + "");
            params.put("type", type + "");

            HttpApi2.getApiService(HostType.TELE_CONFIG).getAlertList(headers, params).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<AlertListInfo>() {
                        @Override
                        public void onSubscribe(Subscription s) {
                            s.request(Long.MAX_VALUE);
                        }

                        @Override
                        public void onNext(AlertListInfo alertListInfo) {
                            try {
                                Log.e(TAG, "===postMineListInfo:" + alertListInfo.toString());
                                if (alertListInfo.getCode().equals(Constant.CODE_SUCCESS)) {
                                    total_page = alertListInfo.getData().getTotal();
                                    if (refreshType && mData != null) {
                                        mData.clear();
                                    }
                                    if (alertListInfo.getData().getList() != null && alertListInfo.getData().getList().size() > 0) {
                                        mData.addAll(alertListInfo.getData().getList());
                                        mRlEmptyLayout.setVisibility(View.GONE);
                                    }
                                    setAdapter();
                                } else {
                                    ToastUtil.showShort(alertListInfo.getMsg());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(Throwable t) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        } else {
            ToastUtil.showShort(getResources().getString(R.string.network_fial_message));
        }
    }

    /**
     * 列表适配器
     */
    private void setAdapter() {
        mRvList.setAdapter(mAdapter = new BaseQuickAdapter<AlertListInfo.DataBean.ListBean, BaseViewHolder>(R.layout.item_alarm_list, mData) {
            @Override
            protected void convert(BaseViewHolder helper, AlertListInfo.DataBean.ListBean item) {
                LinearLayout lay_list = helper.getView(R.id.lay_list);
                TextView tv_date = helper.getView(R.id.tv_date);
                TextView tv_device_number = helper.getView(R.id.tv_device_number);
                TextView tv_device_name = helper.getView(R.id.tv_device_name);
                try {
                    tv_date.setText(item.getCreatedate());
                    tv_device_number.setText(item.getDevice_code());
                    tv_device_name.setText(item.getName());

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
